<# ============================================================================================= # It is recommended to test the script on a local machine to verify its functionality and effects. # ManageEngine Endpoint Central will not be responsible for any damage or data loss caused by the script's execution. # Description : Script to rename multiple Windows computers using CSV mappings. # Dependency File : ComputerRename.csv # Log File : C:\Program Files (x86)\ManageEngine\UEMS_Agent\logs\RenameComputerLogger.log # Type : Computer # Execution Requirements: * The end user must create the 'ComputerRename.csv' file and attach it as a dependency file during deployment. * The script must be executed with elevated privileges. * Initially, test the script using the SYSTEM account. * If the script fails due to insufficient permissions under SYSTEM, execute it using "RUN AS" Option with Common admin account # CSV File Creation – Computer Rename Configuration 1. Create a CSV file named ComputerRename.csv. 2. The CSV file must contain the following two columns: * CurrentComputerName * NewComputerName 3. Use the sample data below as a reference and replace the sample computer names with the appropriate names for your environment. CurrentComputerName,NewComputerName DESKTOP01,KB-PC16 DESKTOP02,KB-PC06 DESKTOP03,KB-PC1 # Important: * "CurrentComputerName" must contain the computer's existing hostname. * "NewComputerName" must contain the expected new hostname to be assigned to the computer. * Ensure that the existing computer name matches the device's current hostname. * Ensure that each new computer name is valid and unique within the environment. * Save the file in CSV format with the exact filename "ComputerRename.csv" & upload as dependency file # Troubleshooting: * Check RenameComputerLogger.log at C:\Program Files (x86)\ManageEngine\UEMS_Agent\logs\RenameComputerLogger.log to identify the reason for the rename failure. * If the computer name was changed but is not reflected, restart the affected machine once. There is no need to restart all connected devices. ============================================================================================== #> $ErrorActionPreference = "Stop" $LogFolder = "C:\Program Files (x86)\ManageEngine\UEMS_Agent\logs" $LogFile = Join-Path $LogFolder "RenameComputerLogger.log" $CSVFile = "ComputerRename.csv" # ------------------------------------------------------------ # Initialize logging directory # ------------------------------------------------------------ try { if (-not (Test-Path -LiteralPath $LogFolder)) { New-Item -Path $LogFolder -ItemType Directory -Force | Out-Null } } catch { Write-Warning "Unable to initialize logging directory: $($_.Exception.Message)" return } # ------------------------------------------------------------ # Logging function: append timestamped entries # ------------------------------------------------------------ function Write-Log { param ( [Parameter(Mandatory = $true)] [string]$Message ) $Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff" $LogMessage = "[$Timestamp] $Message" try { Add-Content -LiteralPath $LogFile ` -Value $LogMessage ` -Encoding UTF8 } catch { Write-Warning "Unable to write log entry: $($_.Exception.Message)" } } # ------------------------------------------------------------ # Main execution # ------------------------------------------------------------ try { Write-Log "==================================================" Write-Log "Computer rename script execution started." # Log execution details Write-Log "Execution account: $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)" Write-Log "Current computer name: $env:COMPUTERNAME" Write-Log "Current working directory: $(Get-Location)" Write-Log "PowerShell script directory: $PSScriptRoot" Write-Log "PowerShell script path: $PSCommandPath" Write-Log "CSV file path: $CSVFile" Write-Log "Log file path: $LogFile" # -------------------------------------------------------- # Validate administrator privileges # -------------------------------------------------------- Write-Log "Checking administrator privileges." $Identity = [System.Security.Principal.WindowsIdentity]::GetCurrent() $Principal = New-Object System.Security.Principal.WindowsPrincipal($Identity) $IsAdmin = $Principal.IsInRole( [System.Security.Principal.WindowsBuiltInRole]::Administrator ) if (-not $IsAdmin) { Write-Log "ERROR: Administrator privileges are required." Write-Log "Please rerun the script using Run as administrator." Write-Warning "Please run this script as Administrator." return } Write-Log "Administrator privileges verified successfully." # -------------------------------------------------------- # Validate CSV file # -------------------------------------------------------- Write-Log "Checking CSV file availability." if (-not (Test-Path -LiteralPath $CSVFile -PathType Leaf)) { Write-Log "ERROR: CSV file not found: $CSVFile" Write-Warning "CSV file not found: $CSVFile" return } Write-Log "CSV file found successfully." Write-Log "Importing CSV computer mappings." $ComputerMappings = @( Import-Csv -LiteralPath $CSVFile -ErrorAction Stop ) Write-Log "CSV records loaded: $($ComputerMappings.Count)" if ($ComputerMappings.Count -eq 0) { Write-Log "ERROR: CSV contains no computer mappings." return } # -------------------------------------------------------- # Validate required CSV columns # -------------------------------------------------------- $RequiredColumns = @( "CurrentComputerName", "NewComputerName" ) $CSVColumns = @($ComputerMappings[0].PSObject.Properties.Name) foreach ($Column in $RequiredColumns) { if ($Column -notin $CSVColumns) { Write-Log "ERROR: Required CSV column missing: $Column" return } } Write-Log "CSV column validation successful." # -------------------------------------------------------- # Match current computer name # -------------------------------------------------------- $CurrentName = $env:COMPUTERNAME Write-Log "Searching CSV for current computer: $CurrentName" $MatchingRecords = @( $ComputerMappings | Where-Object { ([string]$_.CurrentComputerName).Trim() -ieq $CurrentName } ) if ($MatchingRecords.Count -eq 0) { Write-Log "No mapping found for computer: $CurrentName" Write-Log "Rename operation skipped." return } if ($MatchingRecords.Count -gt 1) { Write-Log "ERROR: Multiple mappings found for: $CurrentName" Write-Log "Rename operation skipped to avoid ambiguity." return } $NewComputerName = ([string]$MatchingRecords[0].NewComputerName).Trim() Write-Log "Matching CSV record found." Write-Log "Existing computer name: $CurrentName" Write-Log "Requested computer name: $NewComputerName" # -------------------------------------------------------- # Validate requested computer name # -------------------------------------------------------- if ([string]::IsNullOrWhiteSpace($NewComputerName)) { Write-Log "ERROR: Requested computer name is empty." return } if ($NewComputerName.Length -gt 63 -or $NewComputerName -notmatch '^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$') { Write-Log "ERROR: Invalid computer name: $NewComputerName" return } Write-Log "Requested computer name validation successful." # -------------------------------------------------------- # Compare existing and requested names # -------------------------------------------------------- if ($CurrentName -ieq $NewComputerName) { Write-Log "Computer already has the requested name." Write-Log "No rename operation is required." return } Write-Log "Computer name mismatch detected." Write-Log "Starting Rename-Computer operation." # -------------------------------------------------------- # Rename computer # -------------------------------------------------------- Rename-Computer -NewName $NewComputerName -Force -ErrorAction Stop Write-Log "Rename-Computer command completed successfully." Write-Log "Previous computer name: $CurrentName" Write-Log "Requested new computer name: $NewComputerName" Write-Log "A restart may be required for the new name to take effect." Write-Log "No automatic restart was initiated." Write-Log "Computer rename script execution completed successfully." } catch { Write-Log "ERROR: $($_.Exception.Message)" Write-Log "Exception type: $($_.Exception.GetType().FullName)" Write-Log "Computer rename script execution failed." Write-Warning "Computer rename failed. Check RenameComputerLogger.log." }